from openpyxl import *
import logging

logger = logging.getLogger(__name__)

class Writecase:

    def __init__(self, filepath):
        logger.info(f'opeartion file :{filepath}')
        print(f"file:{filepath}")
        self.file = filepath
        # 获取工作簿
        self.wb = load_workbook(self.file)
        # 获取工作表sheet
        sheets = self.wb.sheetnames
        print(f"sheet name:{sheets}")
        self.sheet = sheets[0]
        self.ws = self.wb[self.sheet]

    def getsheet(self):
        return self.sheet

    # 读取sheet文件的内容，节点覆盖, 判断是否是1，读取第一行的字段，是0 ，不处理
    def wc(self):
        rows = self.ws.max_row
        column = self.ws.max_column
        row_column_data = []

        # 读取每行的数据
        for i in range(2, rows + 1):  # 从第二行开始
            row_data = []
            for col in range(1, column + 1):  # 第一列
                cell_value = str(self.ws.cell(row=i, column=col).value)
                # print(f'读取当前的row:{i}:col:{col},value:{cell_value}')
                # =1的情况，把列的首行显示出来
                if cell_value == "1":
                    cell_value = f'，步骤：' + str(self.ws.cell(row=1, column=col).value)
                    # print(f'当前的cell——value==1:{cell_value}')

                if str(self.ws.cell(row=i, column=col).value) == "0":
                    # print(f'当前的cell——value== 0 &\\:{cell_value}')
                    cell_value = ''
                row_data.append(cell_value)

            row_column_data.append(row_data)
        for item in row_column_data:
            print(item)
        return row_column_data
        # 写入excel表格中，指定的地点

    # 获取到数据后 ，写入到新的sheet中，重新进行拆装组合再次写入到sheet中
    def write_testcase_to_excel(self, sheetname, data):
        title_data = ['标题','预置条件', '测试步骤', '预期结果', '测试结果']
        self.tc = self.wb.create_sheet(sheetname, 1)
        print('转换传入的数据....')
        data1 = []
        data1.insert(0, title_data)

        for item in data:
            title = item[0]
            steps = ''.join(item[1:-2])+"\n"
            expected =  item[-1]
            dd = []
            dd.append(title)
            dd.append(' ')
            dd.append(steps)
            dd.append(expected)
            data1.append(dd)

        print(data1)
        for row_index, row_item in enumerate(data1):
            # print(f'最外层 。。。。{row_index},{row_item}')
            for col_index, col_item in enumerate(row_item):
                # print(f'内层 。。。。{col_index},{col_item}')
                self.tc.cell(row=row_index + 1, column=col_index + 1, value=col_item)

        self.wb.save(self.file)
        print('写入数据完成....')


if __name__ == '__main__':
    ts = Writecase('./1.0系统版本V20230615-10-0测试用例-YZP-20240523.xlsx')
    rs = ts.wc()

    ts.write_testcase_to_excel(ts.getsheet()+"-用例转化", rs)
